// pages/secondhand/detail/detail.js
const app = getApp()

Page({
  data: {
    id: null,
    detail: null,
    loading: true,
    isFavorite: false,
    imageUrls: [],
    currentImageIndex: 0
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ id: options.id })
      this.loadDetail()
    } else {
      wx.showToast({
        title: '商品ID不存在',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  onShow() {
    // 页面显示时可以刷新数据
    if (this.data.id) {
      this.loadDetail()
    }
  },

  onShareAppMessage() {
    return {
      title: this.data.detail ? this.data.detail.title : '二手商品',
      path: `/pages/secondhand/detail/detail?id=${this.data.id}`
    }
  },

  // 加载商品详情
  async loadDetail() {
    this.setData({ loading: true })

    try {
      const response = await app.utils.request({
        url: `/secondhand/detail/${this.data.id}`
      })

      if (response && response.code === 200) {
        const detail = response.data

        // 解析图片
        let imageUrls = []
        if (detail.images) {
          try {
            imageUrls = JSON.parse(detail.images)
          } catch (e) {
            console.error('解析图片失败:', e)
          }
        }

        this.setData({
          detail,
          imageUrls,
          loading: false
        })

        // 设置标题
        wx.setNavigationBarTitle({
          title: detail.title || '商品详情'
        })
      } else {
        wx.showToast({
          title: response.message || '加载失败',
          icon: 'none'
        })
        this.setData({ loading: false })
      }
    } catch (error) {
      console.error('加载商品详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },

  // 图片预览
  previewImage(e) {
    const index = e.currentTarget.dataset.index
    wx.previewImage({
      current: this.data.imageUrls[index],
      urls: this.data.imageUrls
    })
  },

  // 图片轮播切换
  onSwiperChange(e) {
    this.setData({
      currentImageIndex: e.detail.current
    })
  },

  // 收藏/取消收藏
  async toggleFavorite() {
    try {
      const url = this.data.isFavorite 
        ? `/secondhand/unfavorite/${this.data.id}`
        : `/secondhand/favorite/${this.data.id}`

      const response = await app.utils.request({
        url,
        method: 'POST'
      })

      if (response && response.code === 200) {
        this.setData({
          isFavorite: !this.data.isFavorite
        })
        wx.showToast({
          title: this.data.isFavorite ? '收藏成功' : '取消收藏',
          icon: 'success'
        })

        // 更新收藏数
        if (this.data.detail) {
          const detail = this.data.detail
          detail.favoriteCount = this.data.isFavorite 
            ? detail.favoriteCount + 1 
            : detail.favoriteCount - 1
          this.setData({ detail })
        }
      }
    } catch (error) {
      console.error('收藏操作失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  // 联系卖家
  contactSeller() {
    const detail = this.data.detail
    if (!detail) return

    const contactInfo = []
    if (detail.wechat) contactInfo.push(`微信: ${detail.wechat}`)
    if (detail.qq) contactInfo.push(`QQ: ${detail.qq}`)
    if (detail.phone) contactInfo.push(`手机: ${detail.phone}`)

    if (contactInfo.length === 0) {
      wx.showToast({
        title: '卖家未留联系方式',
        icon: 'none'
      })
      return
    }

    wx.showModal({
      title: '联系卖家',
      content: contactInfo.join('\n'),
      showCancel: true,
      cancelText: '取消',
      confirmText: '复制微信',
      success: (res) => {
        if (res.confirm && detail.wechat) {
          wx.setClipboardData({
            data: detail.wechat,
            success: () => {
              wx.showToast({
                title: '微信号已复制',
                icon: 'success'
              })
            }
          })
        }
      }
    })
  },

  // 查看卖家信息
  viewSellerInfo() {
    const detail = this.data.detail
    if (!detail || !detail.sellerId) return

    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },

  // 编辑商品（仅卖家）
  editSecondhand() {
    wx.navigateTo({
      url: `/pages/secondhand/edit/edit?id=${this.data.id}`
    })
  },

  // 删除商品（仅卖家）
  async deleteSecondhand() {
    wx.showModal({
      title: '确认删除',
      content: '删除后无法恢复，确定要删除这个商品吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const response = await app.utils.request({
              url: `/secondhand/delete/${this.data.id}`,
              method: 'DELETE'
            })

            if (response && response.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              setTimeout(() => {
                wx.navigateBack()
              }, 1500)
            } else {
              wx.showToast({
                title: response.message || '删除失败',
                icon: 'none'
              })
            }
          } catch (error) {
            console.error('删除商品失败:', error)
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            })
          }
        }
      }
    })
  },

  // 标记为已售出
  async markAsSold() {
    wx.showModal({
      title: '确认标记',
      content: '确定要将此商品标记为已售出吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const response = await app.utils.request({
              url: `/secondhand/mark-sold/${this.data.id}`,
              method: 'POST'
            })

            if (response && response.code === 200) {
              wx.showToast({
                title: '标记成功',
                icon: 'success'
              })
              this.loadDetail()
            } else {
              wx.showToast({
                title: response.message || '标记失败',
                icon: 'none'
              })
            }
          } catch (error) {
            console.error('标记失败:', error)
            wx.showToast({
              title: '标记失败',
              icon: 'none'
            })
          }
        }
      }
    })
  },

  // 下架商品
  async offShelf() {
    try {
      const response = await app.utils.request({
        url: `/secondhand/off-shelf/${this.data.id}`,
        method: 'POST'
      })

      if (response && response.code === 200) {
        wx.showToast({
          title: '下架成功',
          icon: 'success'
        })
        this.loadDetail()
      } else {
        wx.showToast({
          title: response.message || '下架失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('下架失败:', error)
      wx.showToast({
        title: '下架失败',
        icon: 'none'
      })
    }
  },

  // 上架商品
  async onShelf() {
    try {
      const response = await app.utils.request({
        url: `/secondhand/on-shelf/${this.data.id}`,
        method: 'POST'
      })

      if (response && response.code === 200) {
        wx.showToast({
          title: '上架成功',
          icon: 'success'
        })
        this.loadDetail()
      } else {
        wx.showToast({
          title: response.message || '上架失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('上架失败:', error)
      wx.showToast({
        title: '上架失败',
        icon: 'none'
      })
    }
  }
})

